package vn.allmobile.ambnews.activities.list;

import java.util.List;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

import vn.allmobile.ambnews.R;
import vn.allmobile.ambnews.customview.FlipViewInterface;
import vn.allmobile.ambnews.data.Article;
import vn.allmobile.ambnews.data.Paper;
import vn.allmobile.ambnews.network.NetworkAPI;
import vn.allmobile.ambnews.utils.Contants;
import vn.allmobile.ambnews.utils.GlobalApplication;
import vn.allmobile.ambnews.utils.ImageLoadOption;
import vn.allmobile.ambnews.utils.Log;
import vn.allmobile.ambnews.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class ListFlipViewAdapter extends BaseAdapter {
	int _height;
	int _width;
	List<Article> _articles;
	String navigationTitle ;
	Activity _activity;
	FlipViewInterface _flipview;
	//FlipView _flipview;
	
	public  int[] listview;
	public static  int[] listimgavatarId;
	public static  int[] listsourcavatarId;   
	public static  int[] listsourcedateId;
	public static  int[] listsourcenameId;
	public static  int[] listsourceId;
	public static  int[] listtxtDescId;
	public static  int[] listtxtTitleId;
	public static  int[] listtxtnameId;
	public static  int[] listviewId;
	public static  int[] listbackbutton;
	public static  int[] listtxtpaging;
	public static  int[] listnavigation;
    
    
	
	@SuppressWarnings("deprecation")
	public ListFlipViewAdapter(Activity activity,String list_type ) {
		// 
		Display display = activity.getWindowManager().getDefaultDisplay(); 
		_width = display.getWidth();
		_height = display.getHeight();
		
		try{
			if(list_type != null  && list_type.equalsIgnoreCase(Contants.LIST_TYPE_HOT) )
			{// in nÃ³ng
				navigationTitle = "Tin Nóng";
				_articles  = NetworkAPI._listHotArticles;
			}
			else if(list_type != null  && list_type.equalsIgnoreCase(Contants.LIST_TYPE_USER))
			{
				navigationTitle = NetworkAPI._userListPapers
						.get(NetworkAPI._currentPaperIndex)
						.getCategories()
						.get(NetworkAPI._currentCategoryIndex)
						.getTitle();
				_articles  = NetworkAPI._listArticles;
			}
			else
			{
				
				//
				navigationTitle = NetworkAPI._papers
						.get(NetworkAPI._currentPaperIndex)
						.getCategories()
						.get(NetworkAPI._currentCategoryIndex)
						.getTitle();
				_articles  = NetworkAPI._listArticles;
				
				
			}
			
			if(list_type == null)
				list_type = "";
			
			// tracking category clicked
			EasyTracker.getInstance().setContext(GlobalApplication._());			
		    Tracker tracker = EasyTracker.getTracker();
			tracker.sendEvent(Contants.TRACKER_CATEGORY_BUTTONS,NetworkAPI._currentCategoryId + "-" + Contants.TRACKER_ACTIONS_CLICKED, list_type , Utils.currentMillis());

			
		}catch(Exception e){
			
		}
		
		
		
		_activity = activity;
		
		
		
		int[] arrayOfInt1 = new int[4];
	      arrayOfInt1[0] = R.id.listview1;
	      arrayOfInt1[1] =  R.id.listview2;
	      arrayOfInt1[2] = R.id.listview3;
	      arrayOfInt1[3] = R.id.listview4;
	    ListFlipViewAdapter.listviewId = arrayOfInt1;
		
	    int[] arrayOfInt2 = new int[4];
	      arrayOfInt2[0] = R.id.list_txt_name_1;
	      arrayOfInt2[1] =  R.id.list_txt_name_2;
	      arrayOfInt2[2] = R.id.list_txt_name_3;
	      arrayOfInt2[3] = R.id.list_txt_name_4;
	    ListFlipViewAdapter.listtxtnameId = arrayOfInt2;
		
	    int[] arrayOfInt3 = new int[4];
	      arrayOfInt3[0] = R.id.list_txt_title_1;
	      arrayOfInt3[1] =  R.id.list_txt_title_2;
	      arrayOfInt3[2] = R.id.list_txt_title_3;
	      arrayOfInt3[3] = R.id.list_txt_title_4;
	    ListFlipViewAdapter.listtxtTitleId = arrayOfInt3;
	    
	    int[] arrayOfInt4 = new int[4];
	      arrayOfInt4[0] = R.id.list_txt_desc_1;
	      arrayOfInt4[1] = 0;
	      arrayOfInt4[2] =  R.id.list_txt_desc_3;
	      arrayOfInt4[3] =  R.id.list_txt_desc_4;
	      	   
	    ListFlipViewAdapter.listtxtDescId = arrayOfInt4;
	    
	    int[] arrayOfInt5 = new int[4];
	    	arrayOfInt5[0] = R.id.list_source_1;
	    	arrayOfInt5[1] =  R.id.list_source_2;
	    	arrayOfInt5[2] = R.id.list_source_3;
	    	arrayOfInt5[3] = R.id.list_source_4;	
	    ListFlipViewAdapter.listsourceId = arrayOfInt5;
	    
	    int[] arrayOfInt6 = new int[4];
	    	arrayOfInt6[0] = R.id.list_source_avatar_1;
	    	arrayOfInt6[1] =  R.id.list_source_avatar_2;
	    	arrayOfInt6[2] = R.id.list_source_avatar_3;
	    	arrayOfInt6[3] = R.id.list_source_avatar_4;
    	ListFlipViewAdapter.listsourcavatarId = arrayOfInt6;
	    
    	
    	int[] arrayOfInt7 = new int[4];
	    	arrayOfInt7[0] = R.id.list_source_name_1;
	    	arrayOfInt7[1] =  R.id.list_source_name_2;
	    	arrayOfInt7[2] = R.id.list_source_name_3;
	    	arrayOfInt7[3] = R.id.list_source_name_4;
    	ListFlipViewAdapter.listsourcenameId = arrayOfInt7;
    	
    	int[] arrayOfInt8 = new int[4];
	    	arrayOfInt8[0] = R.id.list_date_1;
	    	arrayOfInt8[1] =  R.id.list_date_2;
	    	arrayOfInt8[2] = R.id.list_date_3;
	    	arrayOfInt8[3] = R.id.list_date_4;
    	ListFlipViewAdapter.listsourcedateId = arrayOfInt8;
    	int[] arrayOfInt9 = new int[4];
	    	arrayOfInt9[0] = R.id.list_img_avatar_1;
	    	arrayOfInt9[1] =  R.id.list_img_avatar_2;
	    	arrayOfInt9[2] =  0;
	    	arrayOfInt9[3] =  R.id.list_img_avatar_4;
    	ListFlipViewAdapter.listimgavatarId = arrayOfInt9;
    	
    	
    	int[] arrayOfInt10 = new int[4];
    		arrayOfInt10[0] = R.id.list_back_button_1;
    		arrayOfInt10[1] =  R.id.list_back_button_2;
    		arrayOfInt10[2] =  R.id.list_back_button_3;
    		arrayOfInt10[3] =  R.id.list_back_button_4;
    	ListFlipViewAdapter.listbackbutton = arrayOfInt10;
    	
    	int[] arrayOfInt11 = new int[4];
	    	arrayOfInt11[0] = R.id.list_paging_1;
	    	arrayOfInt11[1] =  R.id.list_paging_2;
	    	arrayOfInt11[2] =  R.id.list_paging_3;
	    	arrayOfInt11[3] =  R.id.list_paging_4;
	    	ListFlipViewAdapter.listtxtpaging = arrayOfInt11;
	
	    int[] arrayOfInt12 = new int[4];
	    	arrayOfInt12[0] = R.id.navigation_1;
	    	arrayOfInt12[1] =  R.id.navigation_2;
	    	arrayOfInt12[2] =  R.id.navigation_3;
	    	arrayOfInt12[3] =  R.id.navigation_4;
	    	ListFlipViewAdapter.listnavigation = arrayOfInt12;
    	
    	//listbackbutton    	
    	listview = new int[_articles.size()];
    	
    	
    	int i = 0;
    	for(Article article : _articles)
    	{
    		String image = article.getImage();
    		int imgheight = Integer.parseInt(article.getHeight());
			int imgwidth = Integer.parseInt(article.getWidth());
			
    		if(image.equals("") || image == null )
    		{
    			listview[i] = 2;
    		}
    		else if(imgheight > imgwidth)
    		{
    			listview[i] = 1;
    		}
    		else if(imgheight == 0 || imgwidth == 0)
    		{
    			listview[i] = 3;
    		}
    		else
    		{
    			listview[i] = 0;
    		}
    		i++;
    	}
  	
	}
	
	public void setArticles(List<Article> article)
	{
		_articles = article;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return _articles != null?_articles.size():1;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	
	
	/* (non-Javadoc)
	 * @see android.widget.BaseAdapter#getItemViewType(int)
	 */
	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.widget.BaseAdapter#getViewTypeCount()
	 */
	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final Context context = parent.getContext();
		View localView = convertView;
	    ViewHolder localViewHolder;
	    int layoutId = this.listview[position];
		if(localView == null)
		{
			localView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
			//convertView = inflater.inflate(R.layout.page, parent, false);
			localViewHolder = new ViewHolder();
			     						
			for(int i=0;i< ListFlipViewAdapter.listviewId.length;i++)
		      {
	    	  	localViewHolder.listview[i] =  localView.findViewById(ListFlipViewAdapter.listviewId[i]);
	    	  	localViewHolder.list_img_back[i] =  (ImageView) localView.findViewById(ListFlipViewAdapter.listbackbutton[i]);
				localViewHolder.list_txt_title[i] = (TextView) localView.findViewById(ListFlipViewAdapter.listtxtTitleId[i]);
				localViewHolder.list_txt_paging[i] = (TextView) localView.findViewById(ListFlipViewAdapter.listtxtpaging[i]);
				localViewHolder.list_txt_desc[i] =  (TextView) localView.findViewById(ListFlipViewAdapter.listtxtDescId[i]);
				localViewHolder.list_img_avatar[i] =  (ImageView) localView.findViewById(ListFlipViewAdapter.listimgavatarId[i]);
				localViewHolder.list_source[i] =  localView.findViewById(ListFlipViewAdapter.listsourceId[i]);
				localViewHolder.list_source_name[i] =  (TextView) localView.findViewById(ListFlipViewAdapter.listsourcenameId[i]);
				localViewHolder.list_source_avatar[i] =  (ImageView) localView.findViewById(ListFlipViewAdapter.listsourcavatarId[i]);
				localViewHolder.list_txt_name[i] =  (TextView) localView.findViewById(ListFlipViewAdapter.listtxtnameId[i]);
				localViewHolder.list_date[i] =  (TextView) localView.findViewById(ListFlipViewAdapter.listsourcedateId[i]);
				localViewHolder.list_navigation[i] =  localView.findViewById(ListFlipViewAdapter.listnavigation[i]);
		      }
			
			localView.setTag(localViewHolder);				
			setViewVisibility(localViewHolder, localView);
			
            			
		}else
		{
			localViewHolder = (ViewHolder) localView.getTag();
			
		}
		
		
		
		
		Article article = _articles.get(position);
		
		setViewVisibility(localViewHolder, localView);
		OnClickListener mHandler = new ListItemClickListenner(article,_activity);
		
		localViewHolder.listview[layoutId].setVisibility(View.VISIBLE);
		localViewHolder.listview[layoutId].setOnClickListener(mHandler);
		
		
		
		if(ListFlipViewAdapter.listtxtTitleId[layoutId] > 0)
			localViewHolder.list_txt_title[layoutId].setText(article.getTitle());
		if(ListFlipViewAdapter.listtxtnameId[layoutId] > 0)
		{
			localViewHolder.list_txt_name[layoutId].setText(navigationTitle);
			/*localViewHolder.list_txt_name[layoutId].setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					_activity.onBackPressed();
				}
			});*/
		}
			
				
		if(ListFlipViewAdapter.listbackbutton[layoutId] > 0)
			localViewHolder.list_navigation[layoutId].setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					_activity.onBackPressed();
					
				}
			});
			localViewHolder.list_img_back[layoutId].setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					_activity.onBackPressed();					
				}
			});
		if(ListFlipViewAdapter.listtxtDescId[layoutId] > 0)
		{
			String description = article.getDescription().trim();
			try{
				if(description.length() > 100)
					description= description.substring(0, 160).trim()+ " ...";
			}catch(Exception e){e.printStackTrace();}
			
			//
			localViewHolder.list_txt_desc[layoutId].setText(description);
		}
			
		if(ListFlipViewAdapter.listimgavatarId[layoutId]>0)
		{
			String image = article.getImage();
			String imageURL = "http://news.allmobile.vn/" + image + "?mode=resize";
			imageURL += "&width=" + _width + "&height=" + _height/2;	
				
				ImageLoader.getInstance().displayImage(imageURL, localViewHolder.list_img_avatar[layoutId],ImageLoadOption.options, new ImageLoadingListener() {
				    @Override
				    public void onLoadingStarted(String imageUri, View view) {
				    	Log.v("loading...");				    
				    }
				    @Override
				    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				    	((ImageView) view).setImageResource(R.drawable.no_image_640x560);
				    	_flipview.refreshPage(position);
				    }
				    @Override
				    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				    	_flipview.refreshPage(position);
				    }
				    @Override
				    public void onLoadingCancelled(String imageUri, View view) {
				    	//((ImageView) view).setImageResource(R.drawable.no_image_640x560);
				    }
				});
		}
			
		if(ListFlipViewAdapter.listsourcavatarId[layoutId] > 0)
		{
			Paper pp = NetworkAPI._papersMap.get(article.getPaperId());
			String slug = pp.getSlug();
			String paper_name = pp.getTitle();
			localViewHolder.list_source_name[layoutId].setText(paper_name);
			int test = context.getResources().getIdentifier("logo_"+slug, "drawable", context.getPackageName());			
			Log.v("article.getSlug():" + article.getSlug()+ test);
			if(test != 0)
			{
				localViewHolder.list_source_avatar[layoutId].setImageResource(test);
			}
		}
		if(ListFlipViewAdapter.listsourcedateId[layoutId]>0)
		{
			localViewHolder.list_date[layoutId].setText(Utils.time_elapsed_string(article.getPubdate()));
		}
		//Log.v("date time:" + Utils.time_elapsed_string(article.getPubdate()));
		localViewHolder.list_txt_paging[layoutId].setText("Trang " + (position+1) + "/" + getCount());
		
		int layoutId_tmp ;
		try{
			for(int i = 1; i < 4 ; i ++)
			{
				if(position+ i <= getCount())
				{
					layoutId_tmp = this.listview[position+ i];
					
					if(ListFlipViewAdapter.listimgavatarId[layoutId_tmp]>0)
					{
						
						Article article_tmp = _articles.get(position+ i);
						String image_tmp = article_tmp.getImage();
						Log.v("preload:" + image_tmp);
						String imageURL_tmp = "http://news.allmobile.vn/" + image_tmp + "?mode=resize";
						imageURL_tmp += "&width=" + _width + "&height=" + _height/2;
						
						ImageLoader.getInstance().loadImage(imageURL_tmp,ImageLoadOption.options,new ImageLoadingListener() {
							
							@Override
							public void onLoadingStarted(String arg0, View arg1) {
								// TODO Auto-generated method stub
								
							}
							
							@Override
							public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
								// TODO Auto-generated method stub
								
							}
							
							@Override
							public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
								// TODO Auto-generated method stub
								
							}
							
							@Override
							public void onLoadingCancelled(String arg0, View arg1) {
								// TODO Auto-generated method stub
								
							}
						});
					}
				}
				
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return localView;
		
	}
	
	private void setViewVisibility(ViewHolder paramViewHolder, View paramView)
    {
      for(int i=0;i< ListFlipViewAdapter.listviewId.length;i++)
      {
    	  paramViewHolder.listview[i].setVisibility(View.GONE); 
      }
    }


}
 

class ViewHolder
{
  
  public ImageView[] list_img_back = new ImageView[ListFlipViewAdapter.listbackbutton.length];	
  public TextView[] list_date = new TextView[ListFlipViewAdapter.listsourcedateId.length];
  public TextView[] list_txt_paging = new TextView[ListFlipViewAdapter.listtxtpaging.length];
  public ImageView[] list_img_avatar = new ImageView[ListFlipViewAdapter.listimgavatarId.length];
  public View[] list_source = new View[ListFlipViewAdapter.listsourceId.length];
  public ImageView[] list_source_avatar = new ImageView[ListFlipViewAdapter.listsourcavatarId.length];
  public TextView[] list_source_name = new TextView[ListFlipViewAdapter.listsourcenameId.length];
  public TextView[] list_txt_desc = new TextView[ListFlipViewAdapter.listtxtDescId.length];
  public TextView[] list_txt_name = new TextView[ListFlipViewAdapter.listtxtnameId.length];
  public TextView[] list_txt_title = new TextView[ListFlipViewAdapter.listtxtTitleId.length];
  public View[] listview = new View[ListFlipViewAdapter.listviewId.length];
  public View[] list_navigation = new View[ListFlipViewAdapter.listnavigation.length];

  ViewHolder()
  {
	  
  }
}